package com.android_map_app.activities;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android_map_app.R;
import com.android_map_app.data.ResultType;

public class GroupActivity extends Activity {

	private TextView mGroupName;
	private ListView mMemberList;
	private String[] mMembers;
	private SharedPreferences mPrefs;
	
	static final int DIALOG_DATA_ID = 9;
	static final int DIALOG_JOIN_ID = 8; //random nr
	static final int DIALOG_LEAVE_ID = 7; //random nr
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle extras = getIntent().getExtras();
		setContentView(R.layout.group);
		
		mPrefs = getSharedPreferences(MainActivity.USER_PREF, MODE_PRIVATE);
		
		mMemberList = (ListView) findViewById(R.id.member_list);
		mGroupName = (TextView) findViewById(R.id.group_name);
		
		mGroupName.setText(extras.getString("groupName"));
		
		new fillMembers().execute(mGroupName.getText().toString());
        
        Button confirmButton = (Button) findViewById(R.id.join_group);
        Button leaveButton = (Button) findViewById(R.id.leave_group);
		
		confirmButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new SendJoinRequest().execute(mGroupName.getText().toString());	
			}
		});	
		
		leaveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new UnjoinGroup().execute(mGroupName.getText().toString());
				
			}
		});
	}

	private String[] getGroupMembers() {
		try {
			URL url = new URL("http://" + getBaseContext().getString(R.string.server_name)
					+ "/update?action=getGroupMembers&groupName="
					+ mGroupName.getText());
			BufferedReader br = new BufferedReader(
					new InputStreamReader(url.openStream()));
			JSONArray members = (new JSONObject(br.readLine())).getJSONArray("members");
			String[] result = new String[members.length()];
			for (int i = 0; i < members.length(); i++) result[i] = members.get(i).toString();
			return result;
		} catch (Throwable e) {
			displayToast(e.getMessage());
			return null;
		}
	}
	
	private void displayToast(String message) {
		Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL, 0, 0);
		toast.show();
	}
	
	private class SendJoinRequest extends AsyncTask<String, Integer, ResultType> {
		@Override
		protected ResultType doInBackground(String... params) {
			ResultType result;
			try {
				URL url = new URL("http://" + getBaseContext().getString(R.string.server_name)
						+ "/addtogroup?idCode="
						+ getSharedPreferences(MainActivity.USER_PREF, MODE_PRIVATE)
						.getString("idCode", "") + "&groupName="
						+ params[0]);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(url.openStream()));
				String input = br.readLine();
				if (!input.equals("FAIL")) {
					SharedPreferences.Editor editor
						= getSharedPreferences(MainActivity.USER_PREF, MODE_PRIVATE).edit();
					editor.putString("activeGroup", params[0]);
					editor.commit();
					result = ResultType.SUCCESS;
				} else {
					result = ResultType.WRONG;
				}
			} catch (Throwable e) {
				result = ResultType.ERROR;
			}
			return result;
		}
		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_JOIN_ID);
		}
		@Override
		protected void onPostExecute(ResultType result) {
			super.onPostExecute(result);
			dismissDialog(DIALOG_JOIN_ID);
			switch (result) {
			case SUCCESS:
				displayToast("You joined the group " + mGroupName.getText().toString());
				Intent intent = new Intent(getApplicationContext(), TabViewActivity.class);
				intent.putExtra("tab", 1);
				startActivity(intent);
				finish();
				break;
			case WRONG:
				displayToast("Nonexistant group (Are you a wizard?)");
				break;
			case ERROR:
				displayToast("Connection error.");
				break;
			}
		}
	}
	
	private class fillMembers extends AsyncTask<String, Integer, ResultType> {
		@Override
		protected ResultType doInBackground(String... params) {
			mMembers = getGroupMembers();
			if (mMembers != null) return ResultType.SUCCESS;
			else {
				return ResultType.ERROR;
			}
		}
		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_DATA_ID);
		}
		@Override
		protected void onPostExecute(ResultType result) {
			super.onPostExecute(result);
			dismissDialog(DIALOG_DATA_ID);
			switch (result) {
			case SUCCESS:
				mMemberList.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.grouplist_item, mMembers));
				break;
			case ERROR:
				displayToast("Connection error.");
				break;
			}
		}
	}
	
	private class UnjoinGroup extends AsyncTask<String, Integer, ResultType> {
		@Override
		protected ResultType doInBackground(String... params) {
			try {
				URL url = new URL("http://" + getBaseContext().getString(R.string.server_name)
						+ "/update?action=unjoin"
						+ "&idCode=" + mPrefs.getString("idCode", "")
						+ "&groupName=" + params[0]);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(url.openStream()));
				String result = br.readLine();
				br.close();
				if (!result.equals("FAIL")) {
					if (mPrefs.getString("activeGroup", "").equals(params[0])) {
						SharedPreferences.Editor editor = mPrefs.edit();
						editor.remove("activeGroup");
						editor.commit();
					}
					return ResultType.SUCCESS;
				}
				else {
					return ResultType.ERROR;
				}
			} catch (Throwable e) {
				displayToast("Connection error");
				return ResultType.ERROR;
			}
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_LEAVE_ID);
		}
		@Override
		protected void onPostExecute(ResultType result) {
			super.onPostExecute(result);
			dismissDialog(DIALOG_LEAVE_ID);
			switch (result) {
			case SUCCESS:
				displayToast("You have left the group.");
				Intent intent = new Intent(getApplicationContext(), TabViewActivity.class);
				intent.putExtra("tab", 1);
				startActivity(intent);
				break;
			case ERROR:
				displayToast("You have to join before you can leave");
				break;
			}
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog dialog;
		switch (id) {
		case DIALOG_JOIN_ID:
			dialog = new ProgressDialog(this);
			dialog.setMessage(GroupActivity.this.getString(R.string.stringJoinGroupWait));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		case DIALOG_DATA_ID:
			dialog = new ProgressDialog(this);
			dialog.setMessage(GroupActivity.this.getString(R.string.stringDataWait));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		case DIALOG_LEAVE_ID:
			dialog = new ProgressDialog(this);
			dialog.setMessage(GroupActivity.this.getString(R.string.stringLeaveGroupWait));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		return null;
	}
}
